package com.gxa.service.impl;

import com.gxa.common.R;
import com.gxa.mapper.EmpMapper;
import com.gxa.pojo.Empl;
import com.gxa.pojo.Premission;
import com.gxa.pojo.Role;
import com.gxa.service.loginService;
import com.gxa.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

/**
 * @author xiejinfeng
 * @create 2021-06-07 13:01
 * @descrip:
 */
@Service
public class loginServiceImpl implements loginService {

    @Autowired
    private EmpMapper emplMapper;

    @Override
    public R login(Empl empl, HttpSession session) {


        Empl empl1 = emplMapper.findByName(empl.getEmplName());

        if (empl1 == null){
            return new R(1001,"该用户不存在");
        }

        if (empl1.getEmplStatus() != null && empl1.getEmplStatus().equals(0)){
            return new R(1001,"账户被锁定");
        }

        if (!empl1.getEmplPwd().equals(MD5Util.MD55(empl.getEmplPwd()))){
            return new R(1001,"密码错误");
        }

        session.setAttribute("emplName",empl1.getEmplRealName());

        session.setAttribute("nowEmplId",empl1.getId());

        session.setAttribute("deptName",empl1.getDept().getDeptName());

        session.setAttribute("roles",getRoleStr(empl1));


        session.setAttribute("isSuper",isSuper(empl1));

        empl.setLastLoginTime(new Timestamp(System.currentTimeMillis()));
        empl.setId(empl1.getId());
        emplMapper.update(empl);

        if (!isSuper(empl1)){
            session.setAttribute("permissions",getPremissions(empl1));
        }

        return new R(200,"登录成功");
    }

    private List<Role> getRoles(Empl empl){
        return empl.getRoles();
    }


    private Boolean isSuper(Empl empl){
        List<Role> roles = getRoles(empl);
        for (Role role : roles) {
            if (role.getRoleId().equals(1)){
                return true;
            }
        }
        return false;
    }


    private String getRoleStr(Empl empl){
        List<Role> roles = getRoles(empl);
        String roleStr = "";
        for (Role role : roles) {
            roleStr += role.getRoleName()+",";
        }
        return roleStr.substring(0,roleStr.length()-1);
    }


    private List<Premission> getPremissions(Empl empl){
        List<Role> roles = getRoles(empl);
        List<Premission> premissions = new ArrayList<>();
        for (Role role : roles) {
            if (role.getPremissions() == null) {
                continue;
            }
            premissions.addAll(role.getPremissions());
        }
        return premissions;
    }

}
